package com.ledim.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.LedimUserBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBitmapUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 个人信息页
 */
public class UserInformationActivity extends LeDimBaseActivity {

    public static final String USER_INFO = "user_info";
    public static final int REQUESTCODE_USER = 101;
    private static final int AVATAR_ALBUM = 1;
    private static final int AVATAR_PHOTOGRAPH = 2;
    private static final int AVATAR_ZOOM = 3;
    private ImageView mBack;
    private LedimUserBean mUser;
    private View mPhotoLayout;
    private SimpleDraweeView mPhoto;
    private View mNameLayout;
    private TextView mName;
    private View mSexLayout;
    private TextView mSex;
    private File mAlbumFile;
    private File mPhotographFile;
    private String mPhotographPath;
    private String mImagePath;
    private LoadingBar mLoading;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_user_information;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        mUser = (LedimUserBean) getIntent().getSerializableExtra(USER_INFO);
        mBack = (ImageView) findViewById(R.id.info_back_image);
        mPhotoLayout = findViewById(R.id.info_photo_layout);
        mPhoto = (SimpleDraweeView) findViewById(R.id.info_photo);
        mNameLayout = findViewById(R.id.info_nickname_layout);
        mName = (TextView) findViewById(R.id.info_nickname);
        mSexLayout = findViewById(R.id.info_sex_layout);
        mSex = (TextView) findViewById(R.id.info_sex);

        mBack.setOnClickListener(this);
        mPhotoLayout.setOnClickListener(this);
        mNameLayout.setOnClickListener(this);
        mSexLayout.setOnClickListener(this);

        if (mUser.avatar != null && !TextUtils.isEmpty(mUser.avatar.thumb)) {
            FrescoUtil.loadUrl(mUser.avatar.thumb, mPhoto);
        }
        if (mUser.nickname != null) {
            mName.setText(mUser.nickname);
        }
        if (mUser.gender.equals("1")) {
            mSex.setText("男");
        } else if (mUser.gender.equals("2")) {
            mSex.setText("女");
        } else {
            mSex.setText("保密");
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.info_back_image:
                finish();
                break;
            case R.id.info_photo_layout:
                choosePicture();
                break;
            case R.id.info_nickname_layout:
                intent = new Intent(this, UserNameActivity.class);
                intent.putExtra(UserNameActivity.USER_NAME, mUser);
                startActivityForResult(intent, REQUESTCODE_USER);
                break;
            case R.id.info_sex_layout:
                intent = new Intent(this, UserSexActivity.class);
                intent.putExtra(UserSexActivity.USER_SEX, mUser);
                startActivityForResult(intent, REQUESTCODE_USER);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UserInformationActivity.REQUESTCODE_USER) {
            if (resultCode == UserNameActivity.REQUESTCODE_USER_NAME) {
                mName.setText(data.getStringExtra("content"));
                mUser.nickname = data.getStringExtra("content");
            } else if (resultCode == UserSexActivity.REQUESTCODE_USER_SEX) {
                mSex.setText(data.getStringExtra("content"));
                if (data.getStringExtra("content").equals("男")) {
                    mUser.gender = 1 + "";
                } else if (data.getStringExtra("content").equals("女")) {
                    mUser.gender = 2 + "";
                } else {
                    mUser.gender = 0 + "";
                }
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == AVATAR_PHOTOGRAPH) {
                if (mPhotographPath != null) {
                    File files = new File(mPhotographPath);
                    if (files.exists()) {
                        mImagePath = mPhotographPath;
                        Uri selectedImage = Uri.fromFile(new File(mImagePath));
                        mImagePath = startPhotoZoom(selectedImage);
                    }
                }
            } else if (requestCode == AVATAR_ALBUM) {
                Uri selectedImage = data.getData();
                mImagePath = startPhotoZoom(selectedImage);

            } else if (requestCode == AVATAR_ZOOM) {
                if (mImagePath != null && mImagePath.length() > 0) {
                    mImagePath = LedimBitmapUtils.zoomImage(mImagePath, 400);//压缩图片
                    File cover = new File(mImagePath);
                    if (mUser.userId != null) {
                        modifyAvatar(cover);
                    }
                }
            }
        }
    }

    private void choosePicture() {

        final Dialog dialog = new Dialog(this, R.style.dialog);
        View contentView = View.inflate(this, R.layout.room_cover_dialog, null);
        dialog.setContentView(contentView);

        android.view.ViewGroup.LayoutParams cursorParams = contentView.getLayoutParams();
        cursorParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(cursorParams);
        dialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim); // 设置窗口弹出动画
        dialog.show();

        ImageView album = (ImageView) dialog.findViewById(R.id.avatar_album);
        ImageView photograph = (ImageView) dialog.findViewById(R.id.avatar_photograph);
        View cancel = dialog.findViewById(R.id.avatar_cancel);

        //从相册选择上传
        album.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent picture =
                        new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(picture, AVATAR_ALBUM);
            }
        });

        //拍照上传
        photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (mPhotographFile == null) {
                    mPhotographFile = new File(LedimFunctionUtils.FILEPATH + "/img/");
                    if (!mPhotographFile.exists()) {
                        mPhotographFile.mkdirs();
                    }
                }
                mPhotographPath = mPhotographFile + LedimFunctionUtils.getImageName();
                File file = new File(mPhotographPath);
                Uri imageuri = Uri.fromFile(file);

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageuri);
                intent.putExtra("return-data", false);
                startActivityForResult(intent, AVATAR_PHOTOGRAPH);

            }
        });
        //取消
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private String startPhotoZoom(Uri uri) {
        String fileName;
        if (mAlbumFile == null) {
            mAlbumFile = new File(LedimFunctionUtils.FILEPATH + "/img/");
            if (!mAlbumFile.exists()) {
                mAlbumFile.mkdirs();
            }
        }
        fileName = "/temp.jpg";
        String filePath = mAlbumFile + fileName;
        File loadingFile = new File(filePath);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 400);
        intent.putExtra("aspectY", 400);
        intent.putExtra("output", Uri.fromFile(loadingFile));// 输出到文件
        intent.putExtra("outputFormat", "PNG");// 返回格式
        intent.putExtra("noFaceDetection", true); // 去除面部检测
        intent.putExtra("return-data", false); // 不要通过Intent传递截获的图片
        startActivityForResult(intent, AVATAR_ZOOM);
        return filePath;
    }

    /**
     * 修改用户头像
     */
    private void modifyAvatar(File cover) {

        if (mLoading == null) {
            mLoading = new LoadingBar(this);
        }
        mLoading.show();
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/jpg"), cover);
        LedimApiServiceFactory.createService(ApiService.class)
                              .modifyAvatar(photoRequestBody)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimUserBean>>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      mLoading.dismiss();
                                      ToastUtil.toast(e.getMessage());
                                  }

                                  @Override
                                  public void onNext(BaseResultDataInfo<LedimUserBean> data) {
                                      super.onNext(data);
                                      mLoading.dismiss();
                                      if (data != null) {
                                          if (data.success) {
                                              mUser.avatar = data.data.avatar;
                                              LedimSpUtils.setUser(LedimGsonConverterFactory.create().gson
                                                      .toJson(mUser));
                                              FrescoUtil.loadUrl(data.data.avatar.thumb, mPhoto);
                                              ToastUtil.toast("用户头像修改成功");
                                          } else {
                                              ToastUtil.toast(data.message);
                                          }
                                      }
                                  }
                              });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoading != null) {
            mLoading.dismiss();
        }
    }
}
